<template>
    <div class="page-container">
        <ComTitle :list="titleList" />
        <div class="list-item">
            <div>
                <div class="item-name">
                    {{ name }}
                </div>
                <div class="detail_data">
                    <div class="detail_item">
                        <svg-icon icon-class="data-size" />
                        <span class="grey">数据大小</span>
                        <span>{{ dataSize || "0" }}</span>
                    </div>
                    <div class="detail_item">
                        <svg-icon icon-class="time" />
                        <span class="grey">上传时间</span>{{ createTime }}
                    </div>
                </div>
            </div>
            <div>
                <Upload type="primary" v-loading="uploadLoading" @change="uploadFile"
                    ><svg-icon icon-class="Import" />导入模型文件
                </Upload>
            </div>
            <!-- <SCButton type="primary" @click="uploadFiles">
                <svg-icon icon-class="Import" />
                导入模型文件
            </SCButton> -->
        </div>

        <div class="multiple-btns">
            <div class="level-container">
                <SCButton
                    class="level-button"
                    :disabled="state.fileStack.length <= 1 || tableLoading"
                    @click="handleBack"
                >
                    <SCIcon>
                        <ArrowLeft />
                    </SCIcon>
                </SCButton>
                <div class="level-desc">{{ filePath }}</div>
            </div>
            <div>
                <SCButton class="default-btn" @click="download(true)"> 下载 </SCButton>
                <SCButton class="default-btn" @click="del(true)"> 删除 </SCButton>
            </div>
        </div>

        <el-table
            :data="data"
            v-loading="tableLoading"
            ref="multipleTableRef"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="80"> </el-table-column>

            <el-table-column prop="name" label="模型名称" min-width="360">
                <template v-slot="{ row }">
                    <div v-if="row.type === 2" class="file-name folder" @click="openFolder(row)">
                        <!-- 文件夹 -->
                        <svg-icon icon-class="folder" />
                        {{ row.name }}
                    </div>
                    <div class="file-name" v-else>
                        <svg-icon icon-class="file_done" />
                        {{ row.name }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="size" label="数据大小" min-width="100"></el-table-column>
            <el-table-column prop="updateTime" label="创建时间" min-width="160"></el-table-column>
            <el-table-column label="操作" min-width="140">
                <template #default="scope">
                    <SCButton class="default-btn" @click="download(false, scope.row)">
                        下载
                    </SCButton>
                    <SCButton class="default-btn" @click="del(false, scope.row)"> 删除 </SCButton>
                </template>
            </el-table-column>
        </el-table>

        <SCPagination
            class="pagination"
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :total="total"
            layout="prev,pager,next,sizes,jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import ComTitle from "../../components/ComTitle.vue";
import { reactive, ref, watch } from "vue";
import { ElTable } from "element-plus";
import Upload from "@/components/Upload.vue";
import { SCMessage, SCMessageBox } from "@sribd/sc-ui/lib";
import {
    DetailItem,
    getModelFileList,
    getModelDetail,
    delModelFiles,
    uploadModelFiles,
    getModelfileDownloadList,
} from "../../api/modelManage";
import { downloadFile } from "../../utils/common";

const titleList = [
    {
        name: "模型管理",
        routeName: "model",
    },
    {
        name: "模型详情",
    },
];

const route = useRoute();
const id = parseInt(route.params.id as string);
const pageNum = ref(1);
const pageSize = ref(10);
const tableLoading = ref(false);

const name = ref("");
const dataSize = ref("");
const createTime = ref("");
const total = ref(0);
const data = ref<DetailItem[]>([]);
const filePath = ref("");

const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<DetailItem[]>([]);

interface State {
    fileStack: Array<{ id: number; name?: string }>;
}
const state = reactive<State>({
    fileStack: [{ id: 0 }],
});

watch(
    () => state.fileStack,
    () => {
        filePath.value = state.fileStack
            .slice(1)
            .map((item) => item.name)
            .join("/");
        console.log(filePath.value);
    },
    { deep: true },
);

const detailLoading = ref(true);
getModelDetail(id)
    .then((res) => {
        name.value = res.name;
        dataSize.value = res.size;
        createTime.value = res.createTime;
    })
    .catch((error) => {
        SCMessage({ message: error.msg || "获取详情失败", type: "error" });
    })
    .finally(() => {
        detailLoading.value = false;
    });

const queryTable = async (parentId = 0, type = 3) => {
    tableLoading.value = true;
    try {
        const res = await getModelFileList({
            modelId: id,
            page: pageNum.value,
            pageSize: pageSize.value,
            parentId,
        });
        data.value = res.list;
        total.value = res.total;
        multipleSelection.value = [];
        changeFileIdStack(type);
        if (parentId === 0) {
            state.fileStack = [{ id: 0 }];
        }
    } catch (error) {
        SCMessage({ message: error.msg || "获取列表失败", type: "error" });
    } finally {
        tableLoading.value = false;
    }
};

/**
 * type 文件路径堆栈变化标识
 * 1-打开子文件， push
 * 2-回退，pop
 * 3-其他，堆栈不变
 */
const changeFileIdStack = (type = 3) => {
    switch (type) {
        case 1:
            if (
                currentFolder &&
                state.fileStack[state.fileStack.length - 1].id !== currentFolder.id
            ) {
                state.fileStack.push(currentFolder);
            }
            break;
        case 2:
            state.fileStack.pop();
            currentFolder = state.fileStack[state.fileStack.length - 1];
            break;
        default:
            break;
    }
};

queryTable(0);

const handleSelectionChange = (val: DetailItem[]) => {
    multipleSelection.value = val;
};

const del = async (multiple = false, row?: DetailItem) => {
    let fileIdList: number[] = [];
    if (multiple) {
        fileIdList = multipleSelection.value.map((item) => item.id);
    } else if (row) {
        fileIdList = [row.id];
    }
    if (!fileIdList.length) {
        SCMessage({ message: "请选择要删除的文件", type: "warning" });
    } else {
        tableLoading.value = true;
        await SCMessageBox.confirm("删除后将不能恢复，确定要删除么？", "Warning", {
            title: "删除模型",
            confirmButtonText: "删除",
            cancelButtonText: "取消",
            type: "warning",
            customClass: "del-message-box",
        });
        try {
            await delModelFiles({
                modelId: id,
                fileIdList,
            });
            SCMessage({ message: "删除成功", type: "success" });
            afterDelete(multiple);
        } catch (error) {
            SCMessage({ message: error.msg || "删除失败", type: "error" });
        } finally {
            tableLoading.value = false;
        }
    }
};

const afterDelete = (multiple = false) => {
    let len: number = 1;
    if (multiple) {
        len = multipleSelection.value.length;
        multipleSelection.value = [];
    }
    if (data.value.length <= len && pageNum.value > 1) {
        pageNum.value--;
    }
    queryTable(currentFolder?.id || 0);
};

let currentFolder: { id: number } | null;
const openFolder = (folder: DetailItem) => {
    pageNum.value = 1;
    currentFolder = folder;
    queryTable(folder.id, 1);
};

const handleBack = () => {
    const upperId = state.fileStack[state.fileStack.length - 2].id;
    queryTable(upperId, 2);
};

const handleSizeChange = (size) => {
    pageNum.value = 1;
    pageSize.value = size;
    queryTable(state.fileStack.length ? state.fileStack[state.fileStack.length - 1].id : 0);
};

const handleCurrentChange = (page) => {
    pageNum.value = page;
    queryTable(state.fileStack.length ? state.fileStack[state.fileStack.length - 1].id : 0);
};

const mulDownLoading = ref(false);
const download = async (multiple: boolean, row?: DetailItem) => {
    let fileIdList: number[] = [];
    if (multiple) {
        fileIdList = [...multipleSelection.value.map((item) => item.id)];
    } else if (row) {
        fileIdList = [row.id];
    }
    if (!fileIdList.length) {
        SCMessage({ message: "请选择要下载的文件", type: "warning" });
    } else {
        if (multiple) {
            mulDownLoading.value = true;
        }
        try {
            const res = await getModelfileDownloadList({
                modelId: id,
                fileIdList,
            });
            downloadFile(res);
        } catch (error) {
            SCMessage({ message: error.msg || "下载失败", type: "error" });
        } finally {
            mulDownLoading.value = false;
        }
    }
};

const uploadLoading = ref(false);
const uploadFile = async (file: File[]) => {
    try {
        uploadLoading.value = true;
        await uploadModelFiles({ modelId: id, folder: file });
        SCMessage({
            message: "模型文件上传成功!",
            type: "success",
        });
        queryTable();
    } catch (e) {
        SCMessage({
            message: e.msg || "模型文件上传失败！",
            type: "error",
        });
    } finally {
        uploadLoading.value = false;
    }
};
</script>

<style lang="scss" scoped>
.list-item {
    width: 100%;
    // height: 84px;
    border: 1px solid #dadcdf;
    padding: 16px 30px 14px 20px;
    box-sizing: border-box;
    background-image: url("../../assets/modelManage/model_detail_bg@2x.png");
    background-repeat: no-repeat;
    background-position: bottom 0 right 0;
    background-size: 100px 82px;
    margin-bottom: 12px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .item-name {
        font-size: 16px;
        font-weight: bold;
        word-break: break-all;
        display: flex;
        align-items: center;
        margin-bottom: 12px;
    }
    .detail_data {
        display: flex;
        align-items: center;
        .detail_item {
            display: flex;
            align-items: center;
            margin-right: 40px;
            .grey {
                font-size: 12px;
                opacity: 0.7;
                margin-right: 12px;
            }
            :deep(.svg-icon) {
                opacity: 0.7;
                margin-right: 6px;
                &:nth-child(2) {
                    margin-right: 9px;
                }
            }
        }
    }

    :deep(.sc-button) {
        margin-right: 140px;
    }
}

.multiple-btns {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    :deep(.sc-button) {
        border-radius: 2px;
        min-width: 72px;
    }
    .level-container {
        display: flex;
        flex: 1;
        align-items: center;
        margin-right: 20px;
        :deep(.level-button) {
            margin-right: 8px;
            min-width: 32px;
            width: 32px;
            padding: 0;
            .sc-icon {
                margin-right: 0;
            }
        }
    }
    .level-desc {
        background: #eef3ff;
        border-radius: 4px;
        height: 32px;
        box-sizing: border-box;
        padding: 0 14px;
        color: rgba(27, 24, 27, 0.7);
        font-size: 12px;
        line-height: 32px;
        flex: 1;
    }
}

:deep(.sc-form) {
    display: block;
}

:deep(.sc-form-item) {
    display: block;
    width: 100%;
    --el-form-inline-content-width: 100%;
    .sc-select {
        width: 100%;
    }
}

.accout-form-item {
    word-break: break-all;
    text-align: justify;
}

.file-name {
    display: flex;
    align-items: center;
    :deep(.svg-icon) {
        margin-right: 8px;
    }
    &.folder {
        cursor: pointer;
    }
    &.folder:hover {
        color: #a446ca;
    }
}
</style>
